package com.nuaa.qianru.run;

import org.opencv.core.*;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import java.util.HashMap;
import java.util.Map;

/*import org.opencv.highgui.HighGui;*/

public class Match {
    //加载由libname参数指定的系统库
    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }


    //建立模板库
    private Map<String, Mat> mats;

    public Map<String, Mat> getMat() {return mats;}

    public Mat getMat(String key) {
        return mats.get(key);
    }

    //规定模板库大小
    public Match() {this.mats = new HashMap<String, Mat>();}

    //添加模板
    public void addMat(String key, Mat mat){
        //模板原图片灰度化
        Imgproc.cvtColor(mat, mat, Imgproc.COLOR_BGR2GRAY);
        /*HighGui.imshow("模板原图片", mat);
        HighGui.waitKey(10);*/
        mats.put(key, mat);
        System.out.println("添加" + key + "模板成功");


    }

    //删除模板
    public void deMat(String key){
        if (mats.containsKey(key)){
            mats.remove(key);
            System.out.println("删除" + key + "模板成功");
        }else{
            System.out.println("该模板不存在！");
        }

    }

    //模板匹配
    public boolean doMatch(Mat image, Mat temp,String fileName){
        // 1 待检测图片灰度化处理
        Mat img = new Mat();
        Imgproc.cvtColor(image, img, Imgproc.COLOR_BGR2GRAY);
        int width=temp.cols();
        int height=temp.rows();
        // 2 创建模板匹配结果Mat
        Mat result=new Mat(width,height, CvType.CV_8U);
        // 3 调用 模板匹配函数
        Imgproc.matchTemplate(img, temp, result, Imgproc.TM_CCOEFF_NORMED);
        // 4 归一化
        //Core.normalize(result, result,0, 1, Core.NORM_MINMAX, -1, new Mat());
        // 5 获取模板匹配结果
        MinMaxLocResult mmr = Core.minMaxLoc(result);
        double index = mmr.maxVal;
        // 6 绘制匹配到的结果
        double x = mmr.maxLoc.x;
        double y = mmr.maxLoc.y;

        //Imgproc.rectangle(img,new Point(x,y),new Point(x+temp.cols(),y+temp.rows()),new Scalar( 0, 0, 255),2,Imgproc.LINE_AA);
        // 7 显示结果
        //System.out.println(index);
        if (index > 0.6) {
            Imgproc.rectangle(image,new Point(x-5,y-5),new Point(x+temp.cols()+5,y+temp.rows()+5),new Scalar( 0, 0, 255),2, Imgproc.LINE_AA,0);
            System.out.println("匹配度为：" + index + "，检测成功");
            Imgcodecs.imwrite("D:\\CG\\img\\recognition\\" + fileName + ".jpg", image);
            //System.out.println("111");
            return true;
            /*HighGui.imshow("待检测图片", img);
            HighGui.imshow("模板匹配", temp);
            HighGui.waitKey(0);*/
        }else{
            Imgproc.rectangle(img,new Point(x-5,y-5),new Point(x+temp.cols()+5,y+temp.rows()+5),new Scalar( 0, 0, 255),2, Imgproc.LINE_AA,0);
            System.out.println("匹配度为：" + index + "，检测失败");
            /*HighGui.imshow("待检测图片", img);
            HighGui.imshow("模板匹配", temp);
            HighGui.waitKey(0);*/
            return false;
        }
    }
}

